package com.cjc.sport.util;

import com.cjc.sport.entity.Article;
import com.cjc.sport.entity.Course;
import com.cjc.sport.entity.Shuffling;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 运动健身工具类
 */
@Slf4j
public class SportUtils {
    /**
     * 超时时间
     */
    private static final int CONNECT_TIMEOUT = 10000; //ms
    /**
     * 编码方式
     */
    private static final String DEFAULT_ENCODING = "UTF-8";

    /**
     * @param urlStr      url连接
     * @param data        数据
     * @param contentType 编码方式
     * @return java.lang.String
     * @Description: 转发
     * @Author: Bruse Queen
     * @Date: 2018/3/21-21:37
     */
    public static String postData(String urlStr, String data, String contentType) {
        BufferedReader reader = null;
        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(CONNECT_TIMEOUT);
            if (contentType != null) {
                conn.setRequestProperty("content-type", contentType);
            }
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
            if (data == null) {
                data = "";
            }
            writer.write(data);
            writer.flush();
            writer.close();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\r\n");
            }
            return sb.toString();
        } catch (Exception e) {
            log.error("Error connection to " + urlStr + ": " + e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e2) {
                log.error("postData", e2);
            }
        }
        return null;
    }


    /**
     * @return uuid
     * @创建时间 2018年1月21日
     * @描述 获取uuid
     * @author dyp
     */
    public static String getUuid() {
        String s = UUID.randomUUID().toString();
        return s.replace("-", "");
    }

    /**
     * 判断字符串是否为空
     *
     * @param judge 字符串
     * @return true 该字符串为空 false 该字符串不为空
     */
    public static boolean judgeNull(String judge) {
        if (judge == null || judge.length() <= 0) {
            return true;
        }
        return false;
    }

    /**
     * 去掉Course对象中的空格
     *
     * @param course 课程表对象
     * @return course 课程表对象
     */
    public static Course removeSpaceForCourse(Course course) {
        course.setCategoryName(course.getCategoryName().trim());
        course.setCourseName(course.getCourseName().trim());
        course.setPicUrl(course.getPicUrl().trim());
        course.setCourseTime(course.getCourseTime().trim());
        course.setCoursePrice(course.getCoursePrice().trim());
        course.setCourseTag(course.getCourseTag().trim());
        course.setDetailUrl(course.getDetailUrl().trim());
        course.setCourseDesc(course.getCourseDesc().trim());
        return course;
    }

    /**
     * 去掉Shuffling中的空格
     *
     * @param shuffling 轮播图对象
     * @return shuffling 轮播图对象
     */
    public static Shuffling removeSpaceForShuffling(Shuffling shuffling) {
        shuffling.setImgUrl(shuffling.getImgUrl().trim());
        shuffling.setTitle(shuffling.getTitle().trim());
        shuffling.setUrl(shuffling.getUrl().trim());
        return shuffling;
    }

    /**
     * 处理JsonArray
     *
     * @param jsonArray json数组
     * @return List<Article> 文章List集合
     */
    public static List<Article> getArticle(JsonArray jsonArray) {

        List<Article> articles = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            String stringData = jsonArray.get(i).getAsJsonObject().get("data").getAsString();

            JsonObject getArticle = new JsonParser().parse(stringData).getAsJsonObject();
//            String client = getArticle.has("client") ? getArticle.get("client").getAsString() : "0";
            String from = getArticle.has("from") ? getArticle.get("from").getAsString() : "0";
            String img = getArticle.has("img") ? getArticle.get("img").getAsString() : "0";
            String sub = getArticle.has("sub") ? getArticle.get("sub").getAsString() : "0";
            String title = getArticle.has("title") ? getArticle.get("title").getAsString() : "0";
//            String to = getArticle.get("to").getAsString();
            String type = getArticle.has("type") ? getArticle.get("type").getAsString() : "0";
            String url = getArticle.has("url") ? getArticle.get("url").getAsString() : "0";

            articles.add(new Article(from, img, sub, title, type, url));
        }
        return articles;
    }
}
